package com.liu.project.aspect;


import com.alibaba.fastjson.JSONObject;
import com.liu.project.pojo.Certificate;
import com.liu.project.pojo.Log;
import com.liu.project.pojo.LoginUser;
import com.liu.project.service.LogService;
import com.liu.project.utils.Message;
import com.liu.project.utils.UserUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 请求的日志处理
 */
@Aspect
@Component
public class WebLogAspect {

    @Autowired
    private LogService logService;


    @Autowired
    UserUtil userUtil;

   // private static Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut(value = "@annotation(com.liu.project.aspect.WebLogAspect.OperLog)")
    public void webLog(){}

    Log log = new Log();

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){

        startTime.set(System.currentTimeMillis());

        //接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        LoginUser loginUser = UserUtil.getLoginUser();

       // log.setUserId(loginUser.getUsername());
        log.setMethod( joinPoint.getSignature().getName());
        log.setIp(request.getRemoteAddr());
        log.setCreated((int) System.currentTimeMillis());
        // 记录下请求内容
//        LOGGER.info("URL : " + request.getRequestURL().toString());
//        LOGGER.info("HTTP_METHOD : " + request.getMethod());
//        LOGGER.info("IP : " + request.getRemoteAddr());
//        LOGGER.info("CLASS_METHOD : " +  joinPoint.getSignature().getName());
//        LOGGER.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "message", pointcut = "webLog()")
    public void doAfterReturning(Message  message) throws Throwable{
        // 处理完请求，返回内容
       // Message message = JSONObject.parseObject((byte[]) ret, Message.class);
        List<Certificate> data = (List<Certificate>) message.getData();
        List array = new ArrayList();
        for (Certificate certificate : data) {
            array.add(  certificate.getName());
        }


        logService.addLog(log);
        System.out.println(log.toString());

        startTime.remove();//用完之后记得清除，不然可能导致内存泄露;
    }

    @Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
    @Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
    @Documented //生成文档
    public @interface OperLog {
        String value() default "";
    }

}
